package com.ruoyi.web.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.web.controller.tool.TestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gxk
 */
@Api("pf")
@RestController
@RequestMapping("/pdf/export")
public class PdfExport {

    @ApiOperation("pdf")
    @Anonymous
    @GetMapping("/testPdf")
    public void testPdf() throws IOException {
// 1.文件的输入流
        InputStream resourceAsStream = TestController.class.getClassLoader().getResourceAsStream("jasper/demo.jasper");
        // 设定目标文件输出的路径
        String desFilePath = "Field01.pdf";
        FileOutputStream outputStream = new FileOutputStream(desFilePath);
        try {

            // 2.创建JasperPrint,向jasper文件中填充数据
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("reportNumber","1234565");

            // 3.将JasperPrint已PDF的形式输出
            JasperPrint jasperPrint = JasperFillManager.fillReport(resourceAsStream, parameters, new JREmptyDataSource());

            // 通过JasperExportManager管理工具进行报表输出文档，此处设定为输出Html文件.
            //JasperExportManager.exportReportToHtmlFile(jasperPrint,desFilePath);
            // JasperExportManager.exportReportToPdfFile(jasperPrint,desFilePath);
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        } catch (JRException e) {
            e.printStackTrace();
        }finally {
            outputStream.flush();
        }
    }

}
